package com.heima.filter;

import com.heima.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/4/12 17:09
 * @Version 1.0
 */
@Slf4j
@Service
public class AuthFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取上下文对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //判断路径需不要鉴权
        String path = request.getURI().getPath();
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }
        //判断是否携带token
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.isEmpty(token)) {
            try {
                //解析成功
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                //判断token是否过期
                int status = AppJwtUtil.verifyToken(claimsBody);
                if (status == -1 || status == 0) {
                    //有效解析userId,放到header
                    Object userId = claimsBody.get("userId");
                    request.mutate().header("userId", userId.toString());
                    return chain.filter(exchange);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        // 解析失败
        // 没有token返回401 未授权状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }



    @Override
    public int getOrder() {
        return 0;
    }
}
